package com.javaweb.homework;

/**
 * @author: XiangHu
 * @date: 2025年02月25日 16:43
 * @describe:
 */



import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

import static com.javaweb.DataSourceUtils.getConnection;


public class JDBCUtils {

    public static int update(String sql, Object... args){
        try(Connection conn = getConnection()){
            PreparedStatement ps = conn.prepareStatement(sql);
            // 设置参数
            for(int i = 0; i < args.length; i++){
                ps.setObject(i+1, args[i]);
            }
            int rows = ps.executeUpdate();
            return rows;
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    public static <T> List<T> query(Class<T> clazz, String sql, Object... params) {
        List<T> list = new ArrayList<>();
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
            ResultSet rs = ps.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            while (rs.next()) {
                T obj = clazz.getDeclaredConstructor().newInstance();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    Object columnValue = rs.getObject(i);
                    java.lang.reflect.Field field = clazz.getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(obj, columnValue);
                }
                list.add(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
